<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { baseURL } from '@/utils/request'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import io, { Socket } from 'socket.io-client'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages, } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { getConsultOrderDetail } from '@/apis/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'


const route = useRoute()
const store = useUserStore()
let socket: Socket
//获取历史聊天记录
const list = ref<Message[]>([])
//保存聊天状态改变
const consult = ref<ConsultOrderItem>()
const consultOrderDetail = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  console.log(res)
  consult.value = res.data
}
provide('consult', consult)
//默认看最新消息响应式
let initMsg = ref(true)
onMounted(() => {
  consultOrderDetail()
  //建立连接
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  //连接成功
  socket.on('connect', () => {
    console.log('连接成功')
  })
  //断开连接
  socket.on('disconnect', () => {
    console.log('断开连接')
  })
  //发送失败
  socket.on('error', (err) => {
    console.log('发送失败', err)
  })
  //监听历史聊天记录
  socket.on('chatMsgList', async ({ data }: { data: TimeMessages[] }) => {
    const arr: Message[] = []
    data.forEach((item, index) => {
      //第一条数据
      if (index === 0) time.value = item.createTime
      arr.push({
        id: item.createTime,
        createTime: item.createTime,
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        }
      })
      arr.push(...item.items)
    })
    // 将处理后的聊天记录追加到 list中
    list.value?.unshift(...arr)
    //没有聊天记录
    loading.value = false
    if (!arr.length) return showToast('没有聊天记录了')
    //如果是第一次进来
    if (initMsg.value) {
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      await nextTick()
      window.scrollTo(0, document.body.scrollHeight)
      initMsg.value = false
    }
  })
  //监听聊天状态改变
  socket.on('statusChange', () => {
    consultOrderDetail()
  })

  //接收发过来的聊天消息
  socket.on('receiveChatMsg', async (event) => {
    socket.emit('updateMsgStatus', event.id)
    list.value.push(event)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)

  })
})
//接收子组件发送过来的文本
const onSendMsg = (msg: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: msg
    }
  })
}
//接收子组件发送过来图片
const onSendImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

//下拉刷新
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}


//评价完成
const updateEva = (score: number) => {
  const item = list.value.find(item => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('updateEva', updateEva)
onUnmounted(() => {
  socket.close()
})
</script>

<template>
  <div class="room-page">
    <!-- 导航栏 -->
    <cp-nav-bar title="问诊室" />
    <RoomStatus :status="consult?.status" :countdown="consult?.countdown"></RoomStatus>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <!-- 消息卡片 -->
      <RoomMessage v-for="item in list" :key="item.id" :item="item"></RoomMessage>
    </van-pull-refresh>
    <!-- 底部操作栏 -->
    <RoomAction :disabled="consult?.status !== OrderType.ConsultChat" @send-msg="onSendMsg" @send-img="onSendImg">
    </RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);

  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
